package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.entity.AddressBook;
import com.itheima.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**地址管理接口
 * @author msi
 */
@RequestMapping("/addressBook")
@RestController
public class AddressBookController {
    @Autowired
    private AddressBookService service;

    @GetMapping("/list")
    public R<List<AddressBook>> getList() {
        List<AddressBook> list = service.getList();

        return R.success(list);
    }

    @PostMapping("")
    public R<AddressBook> insertAddressBook(@RequestBody AddressBook addressBook, HttpServletRequest request) {

        AddressBook insert = service.insert(addressBook);
        return R.success(insert);
    }

    @PutMapping("")
    public R<String> updateAddress(@RequestBody AddressBook addressBook) {
        Boolean update = service.update(addressBook);
        if (update) {
            return R.success("修改成功");
        }
        return R.success("修改失败");
    }

    @GetMapping("/{id}")
    public R<AddressBook> getAddressById(@PathVariable String id) {
        AddressBook addressBook = service.getAddressById(id);

        return R.success(addressBook);
    }

    @DeleteMapping("")
    public R<String> delete(String ids) {
        Boolean flag = service.delete(ids);
        if (flag) {
            return R.success("删除成功");
        }
        return R.error("操作失败");
    }

    @GetMapping("/default")
    public R<AddressBook> getDefaultAddress() {
        AddressBook addressBook = service.getDefaultAddress();

        return R.success(addressBook);
    }

    @PutMapping("/default")
    public R<AddressBook> updateDefault(@RequestBody AddressBook addressBook) {

       Boolean flag = service.updateDefault(addressBook);
        AddressBook newDefaultAddress = service.getDefaultAddress();
        if (flag){
           return R.success(newDefaultAddress);
       }
        return null;
    }

}
